package com.hainatong.shiphelper.api;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import com.hainatong.shiphelper.login.view.LoginActivity;
import com.hainatong.shiphelper.utils.GsonUtil;
import com.jeremyliao.liveeventbus.LiveEventBus;
import org.json.JSONException;

import com.blankj.utilcode.util.LogUtils;
import com.google.gson.JsonParseException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;

public abstract class VMObserver<T> implements Observer<T>
{
    private static String TAG = "VMObserver";

    @Override
    public void onSubscribe(Disposable d)
    {
         onStart(d);
    }

    public abstract void onStart(Disposable d);


    @Override
    public void onNext(T t)
    {
        if( t instanceof ApiResult)
        {
            LogUtils.eTag( TAG ,"onNext = " + GsonUtil.obj2json(t));
        }
        else if( t instanceof HttpResult )
        {
            LogUtils.eTag( TAG ,"onNext = "+GsonUtil.obj2json(t));
        }
        //角色没有权限操作
        //{"status":false,"message":"没有权限操作","code":"306"}
        onSuccess(t);
    }

    @Override
    public void onError(Throwable e)
    {
        //HTTP 401 Unauthorized
        LogUtils.eTag(TAG,"onError = "+e.getMessage());
        String message;
        int code = -1;
        if (e instanceof UnknownHostException) {
            message = "没有网络";
        } else if (e instanceof HttpException) {
            message = "网络错误";
        } else if (e instanceof SocketTimeoutException) {
            message = "网络连接超时";
        } else if (e instanceof JsonParseException
                || e instanceof JSONException) {
            message = "解析错误";
        } else if (e instanceof ConnectException) {
            message = "连接失败";
        }
        /*
        else if (e instanceof ServerException) {
            message = ((ServerException) e).message;
            code = ((ServerException) e).code;
        }
        */
        else {
            message = "未知错误";
        }
        if( e.getMessage().contains("401") && e.getMessage().contains("Unauthorized") )
        {
            message = "登录已过期";
            code = 401;
            //发送 通知 重新登录
            LiveEventBus.get(LoginActivity.Token_Unauthorized).post("Token");
        }
        //HTTP 451 Unavailable For Legal Reasons
        if( e.getMessage().contains("451") && e.getMessage().contains("Unavailable") )
        {
            //角色没有权限操作
            message = "没有权限操作";
            code = 451;
            //发送 通知 重新登录
            LiveEventBus.get("451").post(message);
        }
        //ToastUtils.showShort(message);
        onError( code , message);
    }

    @Override
    public void onComplete()
    {
        //LogUtils.eTag( TAG ,"onComplete ");
    }

    public abstract void onError( int code , String errorMsg);

    public abstract void onSuccess(T t);

}
